package com.ruoyi.system.service.impl;

import java.util.ArrayList;
import java.util.List;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.SysUserRole;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.mapper.SysUserRoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.DsTeacherMapper;
import com.ruoyi.system.domain.DsTeacher;
import com.ruoyi.system.service.IDsTeacherService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 教师信息Service业务层处理
 *
 * @author tyro
 * @date 2025-03-05
 */
@Service
public class DsTeacherServiceImpl implements IDsTeacherService
{
    @Autowired
    private DsTeacherMapper dsTeacherMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;
    /**
     * 查询教师信息
     *
     * @param teacherId 教师信息主键
     * @return 教师信息
     */
    @Override
    public DsTeacher selectDsTeacherByTeacherId(Long teacherId)
    {
        return dsTeacherMapper.selectDsTeacherByTeacherId(teacherId);
    }

    /**
     * 查询教师信息列表
     *
     * @param dsTeacher 教师信息
     * @return 教师信息
     */
    @Override
    public List<DsTeacher> selectDsTeacherList(DsTeacher dsTeacher)
    {
        Long userId = SecurityUtils.getUserId();

        // 如果不是管理员，则添加学院过滤条件
        if(!SecurityUtils.isAdmin(userId)){ // 或使用 SecurityUtils.isAdmin(loginUser.getUser().getUserId())
            dsTeacher.setCollegeId(Long.valueOf(SecurityUtils.getLoginUser().getCollegeId()));
        }
        return dsTeacherMapper.selectDsTeacherList(dsTeacher);
    }

    /**
     * 查询教师信息列表
     *
     * @param dsTeacher 教师信息
     * @return 教师信息
     */
    @Override
    public List<DsTeacher> selectDsTeacherListForClass(DsTeacher dsTeacher)
    {
        Long userId = SecurityUtils.getUserId();

        // 如果不是管理员，则添加学院过滤条件
        if(!SecurityUtils.isAdmin(userId)){ // 或使用 SecurityUtils.isAdmin(loginUser.getUser().getUserId())
            dsTeacher.setCollegeId(Long.valueOf(SecurityUtils.getLoginUser().getCollegeId()));
        }
        return dsTeacherMapper.selectDsTeacherListForClass(dsTeacher);
    }


    /**
     * 新增教师信息
     *
     * @param dsTeacher 教师信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertDsTeacher(DsTeacher dsTeacher)
    {
        dsTeacher.setCreateTime(DateUtils.getNowDate());
        dsTeacher.setDelFlag("0");

        // 插入教师记录
        int rows = dsTeacherMapper.insertDsTeacher(dsTeacher);

        // 创建用户账号
        if (rows > 0) {
            createTeacherAccount(dsTeacher);
        }

        return rows;
    }

    /**
     * 创建教师账号
     */
    private void createTeacherAccount(DsTeacher teacher) {
        // 检查工号是否为空
        if (teacher.getTeacherNo() == null) {
            throw new ServiceException("教师工号不能为空");
        }

        // 检查密码是否为空
        if (StringUtils.isEmpty(teacher.getTeacherPassword())) {
            throw new ServiceException("教师密码不能为空");
        }

        // 检查用户名是否已存在
        String userName = teacher.getTeacherNo().toString();
        SysUser existingUser = sysUserMapper.selectUserByUserName(userName);
        if (existingUser != null) {
            throw new ServiceException(String.format("新增教师'%s'失败，工号已存在", teacher.getTeacherNo()));
        }

        // 创建用户对象
        SysUser user = new SysUser();
        user.setUserName(userName);
        user.setNickName(teacher.getTeacherName());
        user.setPassword(SecurityUtils.encryptPassword(teacher.getTeacherPassword()));
        user.setStatus("0");
        user.setDelFlag("0");
        user.setCollegeId(teacher.getCollegeId());
        user.setCreateBy(teacher.getCreateBy());
        user.setCreateTime(DateUtils.getNowDate());

        // 插入用户
        int userRows = sysUserMapper.insertUser(user);
        if (userRows <= 0) {
            throw new ServiceException("创建教师用户账号失败");
        }

        // 分配教师角色
        SysUserRole userRole = new SysUserRole();
        userRole.setUserId(user.getUserId());
        userRole.setRoleId(2L);
        List<SysUserRole> userRoleList = new ArrayList<>();
        userRoleList.add(userRole);
        sysUserRoleMapper.batchUserRole(userRoleList);
    }

    /**
     * 修改教师信息
     *
     * @param dsTeacher 教师信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateDsTeacher(DsTeacher dsTeacher)
    {
        dsTeacher.setUpdateTime(DateUtils.getNowDate());

        // 查询原有教师信息
        DsTeacher oldTeacher = dsTeacherMapper.selectDsTeacherByTeacherId(Long.valueOf(dsTeacher.getTeacherId()));
        if (oldTeacher == null) {
            throw new ServiceException("教师不存在");
        }

        // 更新教师信息
        int rows = dsTeacherMapper.updateDsTeacher(dsTeacher);

        // 更新用户信息
        if (rows > 0) {
            updateTeacherAccount(oldTeacher, dsTeacher);
        }

        return rows;
    }

    /**
     * 更新教师账号
     */
    private void updateTeacherAccount(DsTeacher oldTeacher, DsTeacher newTeacher) {
        // 检查工号是否为空
        if (oldTeacher.getTeacherNo() == null) {
            return; // 无法更新用户账号
        }

        // 查询关联的用户
        SysUser user = sysUserMapper.selectUserByUserName(oldTeacher.getTeacherNo().toString());
        if (user != null) {
            // 更新昵称和状态
            user.setUserName(newTeacher.getTeacherNo().toString());
            user.setNickName(newTeacher.getTeacherName());
            if (StringUtils.isNotEmpty(newTeacher.getDelFlag())) {
                user.setDelFlag(newTeacher.getDelFlag());
            }
            user.setUpdateBy(newTeacher.getUpdateBy());
            user.setUpdateTime(DateUtils.getNowDate());

            sysUserMapper.updateUser(user);
        }
    }

    /**
     * 批量删除教师信息
     *
     * @param teacherIds 需要删除的教师信息主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteDsTeacherByTeacherIds(Long[] teacherIds)
    {
        // 逻辑删除教师
        for (Long teacherId : teacherIds) {
            DsTeacher teacher = dsTeacherMapper.selectDsTeacherByTeacherId(teacherId);
            if (teacher != null && teacher.getTeacherNo() != null) {
                teacher.setDelFlag("1");
                teacher.setUpdateTime(DateUtils.getNowDate());
                dsTeacherMapper.updateDsTeacher(teacher);

                // 同步停用用户账号
                SysUser user = sysUserMapper.selectUserByUserName(teacher.getTeacherNo().toString());
                if (user != null) {
                    user.setDelFlag("1");
                    user.setUpdateTime(DateUtils.getNowDate());
                    sysUserMapper.updateUser(user);
                }
            }
        }

        return teacherIds.length;
    }

    /**
     * 删除教师信息
     *
     * @param teacherId 教师信息主键
     * @return 结果
     */
    @Override
    public int deleteDsTeacherByTeacherId(Long teacherId)
    {
        DsTeacher teacher = dsTeacherMapper.selectDsTeacherByTeacherId(teacherId);
        if (teacher != null && teacher.getTeacherNo() != null) {
            teacher.setDelFlag("1");
            teacher.setUpdateTime(DateUtils.getNowDate());
            dsTeacherMapper.updateDsTeacher(teacher);

            // 同步停用用户账号
            SysUser user = sysUserMapper.selectUserByUserName(teacher.getTeacherNo().toString());
            if (user != null) {
                user.setDelFlag("1");
                user.setUpdateTime(DateUtils.getNowDate());
                sysUserMapper.updateUser(user);
            }
        }

        return 1;
    }

    /**
     * 重置教师密码
     *
     * @param teacherId 教师ID
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int resetTeacherPassword(Long teacherId)
    {
        // 查询教师信息
        DsTeacher teacher = dsTeacherMapper.selectDsTeacherByTeacherId(teacherId);
        if (teacher == null || teacher.getTeacherNo() == null) {
            throw new ServiceException("教师不存在或教师工号为空");
        }

        // 查询关联的用户
        SysUser user = sysUserMapper.selectUserByUserName(teacher.getTeacherNo().toString());
        if (user == null) {
            throw new ServiceException("教师账号不存在");
        }

        // 默认重置为工号作为密码
        String defaultPassword = teacher.getTeacherNo().toString();
        user.setPassword(SecurityUtils.encryptPassword(defaultPassword));
        user.setUpdateTime(DateUtils.getNowDate());

        return sysUserMapper.updateUser(user);
    }
}
